#include <pthread.h>
#include "sys.h"
#include "stdlib.h"
#include "nstar_http.h"
#include "user_cfg.h"

#include "ebm_task.h"
#include "adp_task.h"



#define POS_POPEN_ARGLEN 256


#define CMD_UDHCPC "udhcpc -n -t 1 -s /usr/share/udhcpc/default.script"   	

static unsigned char eth0_net_enable=0;
unsigned char get_eth0_sta(void) { return eth0_net_enable; }

static void _dbg_ip4(const char* head, const unsigned char* ip)
{
	printf("%s: %d.%d.%d.%d\n", head, ip[0], ip[1], ip[2], ip[3]);
}

void _local_ip_set(const unsigned char* ip, const unsigned char* mask, const unsigned char* gw)
{
	char arg[POS_POPEN_ARGLEN]; 
    /*all numbers are 0 means udhcpc*/
	if( ip[0] == 0 && ip[1] ==0 && ip[2] ==0 ){
		sys_popen(CMD_UDHCPC, sizeof(arg));
        return;
	}
	sprintf(arg, "ifconfig eth0 %d.%d.%d.%d netmask %d.%d.%d.%d",
			ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3] );		
	if(sys_popen(arg, sizeof(arg))) {
        return;
    }
    sprintf(arg, "route del default eth0");
    sys_popen(arg, sizeof(arg));
	sprintf(arg, "route add default gw %d.%d.%d.%d", gw[0], gw[1], gw[2], gw[3] );		
	sys_popen(arg, sizeof(arg));
}


static void net_local_init(void)
{
    const unsigned char *lip, *mask, *gw;
    lip = p_readcfg->local_ip;
    mask = p_readcfg->mask;
    gw = p_readcfg->gateway;
//    _dbg_ip4("local ip", lip);
//    _dbg_ip4("net mask", mask);
//    _dbg_ip4("gateway", gw);
	//_local_ip_set(lip, mask, gw);
}


static void creat_pthread(void *(*p_taskproc)(void* p_param)) {
    int arg = 0;
    pthread_t threads;
    if(pthread_create(&threads, NULL, p_taskproc, (void*)arg) != 0) {
        perror("ERROR; pthread_create");
		exit(-1);
    }

}

const char *get_build_time(void)
{
static char buf[16]= {0}; 
    snprintf(buf,16, "%c%c/%c%c/%c%c",BUILD_Y2,BUILD_Y3,
        BUILD_M0,BUILD_M1,BUILD_D0,BUILD_D1);
	return (const char*)buf;
}

#include "nstar_front_panel.h"

int main(int argc, char **argv) 
{
    set_coredump();
    //app_delay_test();
    board_init();
    net_local_init();
    creat_pthread(web_servo);
    ebm_task_start();
    adp_task_start();
  
    nstar_front_panel_init();
    while(1) {
        usercfg_handle_loop();
        nstar_front_loop();
        usleep(10*1000);
    }
    //creat_pthread(ebm_task);
    while(1) {sleep(1);}
    return 0;
}



